#!/usr/bin/env python
from google.appengine.ext import db
import LectureM

def getTopicsByLecture(lecture):
    topics = db.Query(Topic).filter('lecture =', lecture).filter('deleted =',False).order('index')
    return topics

def resetTopics(lectureKey):
    owner = GeneralM.getEmail()
    lecture = LectureM.getLectureByKey(lectureKey)
    if not lecture:
        return 'error: lecture not found'
    elif not owner:
        return 'error: user is not logged in'
    else:
        db.delete(db.Query(Topic).filter('lecture =', lecture).fetch(limit=1000))
        return 'success'
        
def addTopic(name, lectureKey, index):
    owner = GeneralM.getEmail()
    name = name.strip()
    lecture = LectureM.getLectureByKey(lectureKey)
    if not lecture:
        return 'error: lecture not found'
    elif not owner:
        return 'error: user is not logged in'
    elif name == '':
        return 'error: topic name cannot be empty'
    elif db.Query(Topic).filter('name =', name).filter('lecture =', lecture).count() > 0:
        return 'error: Topic name already exists'
    else:
        topic = Topic(name = name, lecture = lecture, index = index)
        topic.put()
        return topic

def getTopicByKey(key):
    owner = GeneralM.getEmail()
    if owner and key:
        topic = Topic.get(key)
        if CourseM.isOwner(topic.lecture.course):
            return topic
        else:
            return 'error:user accessed lecture key or another user'

def topic2Dict(topic):
    topicDic = {
               'key' : topic.key(),
               'name' : topic.name
           }
    return topicDic

class Topic(db.Model):
    lecture = db.ReferenceProperty(LectureM.Lecture)
    name = db.StringProperty()
    index = db.IntegerProperty()
    deleted=db.BooleanProperty(default=False)
    
import GeneralM
import CourseM